<template>
  <div class="dataRecord">
    <DefineTemplate v-slot="{ item }">
      <div
        class="leaf"
        :class="{
          crlLeaf:
            item.dictValue === 'yx-crl-in' || item.dictValue === 'yx-crl-out'
        }"
      >
        <div class="label">
          {{
            specialFormDictValue.includes(item.dictValue)
              ? ''
              : item.title + '：'
          }}
        </div>
        <div
          class="content"
          :class="{
            crlContent:
              item.dictValue === 'yx-crl-in' || item.dictValue === 'yx-crl-out'
          }"
        >
          <FormItem
            :childNode="!item.childNode ? [item] : item.childNode"
            :unit="item.propUnit"
            :evalItems="evalItems"
            :gcx="gcx"
            :hlcz="hlcz"
            :io="io"
            :pfTime="pfTime"
            @eval="handelEval"
            @eval-fall="handleEvalFall"
            @eval-braden="handleEvalBraden"
            @value-change="handleValueChange"
            @to-add-crl-item="toAddCrlItem"
            @to-remove-crl-item="toRemoveCrlItem"
          />
        </div>
      </div>
    </DefineTemplate>
    <!-- <el-form ref="formRef" label-width="80px">
      <el-form-item
        v-for="(item, index) in formCfgData"
        :key="index"
        :label="item.title"
        style="margin-bottom: 0"
      > -->
    <div class="myForm">
      <div
        v-for="(item, index) in formCfgData"
        :key="index"
        class="item"
        :class="{
          'w-100':
            item.childNode && item.childNode[0].itemCode === 'care_remark'
        }"
      >
        <template v-for="(item2, index2) in item.childNode">
          <ReuseTemplate v-if="item2.leaf" :key="index2" :item="item2" />

          <div v-else :key="index2" class="item2">
            <div
              v-if="!specialFormDictValue.includes(item2.childDictValue)"
              class="label"
            >
              {{ item2.title }}
            </div>
            <div class="content">
              <ReuseTemplate
                v-for="(item3, index3) in item2.childNode"
                :key="index3"
                :item="item3"
              />
            </div>
          </div>
        </template>
      </div>
    </div>
    <!-- </el-form-item>
    </el-form> -->
  </div>
</template>

<script>
import { createReusableTemplate } from '@vueuse/core'
import {
  computed,
  defineComponent,
  nextTick,
  reactive,
  set,
  toRefs,
  watch
} from 'vue'

import {
  getElementFnFromInstance,
  getStoreFromInstance
} from '@/utils/instance'

import FormItem from './FormItem.vue'

const [DefineTemplate, ReuseTemplate] = createReusableTemplate()

export default defineComponent({
  name: 'DataRecord',
  components: {
    FormItem,
    DefineTemplate,
    ReuseTemplate
  },
  props: {
    cfgData: {
      type: Array,
      default: () => []
    },
    recordData: {
      type: Array,
      default: () => []
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    pfTime: {
      type: String,
      default: ''
    }
  },
  setup(props, { emit }) {
    const store = getStoreFromInstance()
    const { $notify, $confirm } = getElementFnFromInstance()

    const state = reactive({
      /**
       * 来源
       */
      from: 'intensiveCare',
      /**
       * @type {ElFormRef | undefined}
       */
      formRef: undefined,
      formCfgData: [],
      specialFormDictValue: ['yx-pgpf', 'vte_braden', 'vte_dd'],
      gcx: {},
      hlcz: {},
      io: {},
      evalItems: {},
      hlczEnumMap: {}
    })

    const evalDialogKeys = computed(() => {
      const result = []
      Object.keys(state.evalItems).forEach(key => {
        if (state.evalItems[key].type === 'yx-pgpf') {
          result.push(key)
        }
      })
      return result
    })

    const user = computed(() => store.getters.user)
    const patCur = computed(() => store.getters.patCur)

    /**
     * 保存方法，供父组件调用
     */
    function save() {
      return {
        gcx: state.gcx,
        hlcz: state.hlcz,
        io: state.io
      }
    }

    function handleTreeData(cfgDataClone) {
      const completeField = list => {
        return list.map(item => {
          if (item.childNode && item.childNode.length > 0) {
            const hasDictValueItem = item.childNode.find(
              item2 => !!item2.dictValue
            )
            if (hasDictValueItem) {
              item.childDictValue = hasDictValueItem.dictValue
            }
            item.childNode = completeField(item.childNode)
            if (item.childNode[0].leaf && item.dictValue) {
              item.leaf = true
            }
          } else {
            if (
              item.dictValue === 'vte_dd' ||
              item.dictValue === 'vte_braden'
            ) {
              item.childNode = [JSON.parse(JSON.stringify(item))]
              initEvalItems(item.dictValue, item)
            }
            if (item.dictValue === 'yx-pgpf') {
              initEvalItems(item.pgId, item)
            }
            if (item.dictValue === 'yx-hlcz') {
              const enumMap = JSON.parse(item.enumMap)
              state.hlczEnumMap[enumMap.itemCode] = enumMap.itemName
            }
            item.leaf = true
            return item
          }
          return item
        })
      }

      state.formCfgData = completeField(cfgDataClone)
      console.log(state.formCfgData)
    }

    function initEvalItems(key, item) {
      const data =
        item.dictValue === 'yx-pgpf'
          ? {
              type: item.dictValue,
              val: '',
              activePgCode: '',
              activePgType: item.pgType,
              activePgId: key,
              propPgRecordId: '',
              visible: false,
              data: {}
            }
          : {
              type: item.dictValue,
              val: '',
              propPgRecordId: '',
              visible: false,
              data: {}
            }
      set(state.evalItems, key, data)
    }

    /**
     * 评估评分 - 普通
     */
    function handelEval(data) {
      state.evalItems[data.activePgId].activePgCode = data.activePgCode
      state.evalItems[data.activePgId].visible = true
    }

    function toCloseEval(key) {
      state.evalItems[key].visible = false
    }

    function toUpdateEval(data, visible = false) {
      const key = data.pgId

      state.evalItems[key].visible = visible
      state.evalItems[key].activePgType = data.pgType
      if (data.pgRecordDetailVos.length > 0) {
        // 已评分
        if (
          data.pgRecordDetailVos.some(
            v => v.detailId !== undefined && v.detailId !== ''
          )
        ) {
          state.evalItems[key].val = data.showValue
          state.evalItems[key].data = data
        }
      } else {
        state.evalItems[key].val = ''
        state.evalItems[key].data = {}
      }
    }

    /**
     * 评估评分 - 跌倒
     */
    function handleEvalFall() {
      state.evalItems['vte_dd'].visible = true
    }

    function toCloseFall() {
      state.evalItems['vte_dd'].visible = false
    }

    function toUpdateFall(data, visible = false) {
      const key = 'vte_dd'

      state.evalItems[key].val = data.result
      state.evalItems[key].data = data
      state.evalItems[key].visible = visible
    }

    /**
     * 评估评分 - Braden
     */
    function handleEvalBraden() {
      state.evalItems['vte_braden'].visible = true
    }

    function toUpdateBraden(data, visible = false) {
      const key = 'vte_braden'

      state.evalItems[key].val = data.result
      state.evalItems[key].data = data
      state.evalItems[key].visible = visible
    }

    function toCloseBraden() {
      state.evalItems['vte_braden'].visible = false
    }

    /**
     * 正常表单元素的value修改
     */
    function handleValueChange({ value, item, crlIndex, crlKey, nature }) {
      if (item.dictValue === 'yx-gcx') {
        if (state.gcx[item.obsvCode]) {
          set(state.gcx[item.obsvCode], 'value', value)
        } else {
          set(state.gcx, item.obsvCode, {
            value: value,
            obsvCode: item.obsvCode
          })
        }
      } else if (item.dictValue === 'yx-hlcz') {
        if (state.hlcz[item.itemCode]) {
          set(state.hlcz[item.itemCode], 'value', value)
        } else {
          set(state.hlcz, item.itemCode, {
            value: value,
            itemCode: item.itemCode,
            itemName: state.hlczEnumMap[item.itemCode]
          })
        }
      } else if (
        item.dictValue === 'yx-crl-in' ||
        item.dictValue === 'yx-crl-out'
      ) {
        set(state.io[item.dictValue][crlIndex], crlKey, value)
        if (nature) {
          set(state.io[item.dictValue][crlIndex], 'nature', nature)
        }
      }
      // console.log(state.gcx)
    }

    function handleRecordData(val) {
      val.forEach(v => {
        if (v.dictValue === 'yx-pgpf') {
          const key = v['pgpf-pgId'][0]
          if (key in state.evalItems && v.val) {
            state.evalItems[key].activePgType = v['pgpf-type'][0]
            state.evalItems[key].propPgRecordId = v.id
          }
        } else if (v.dictValue === 'vte_dd' || v.dictValue === 'vte_braden') {
          const key = v.dictValue
          if (key in state.evalItems && v.val) {
            state.evalItems[key].propPgRecordId = v.id
          }
        } else if (v.dictValue === 'yx-gcx') {
          let values = []
          if (v.val) {
            values = v.val.split(v.splicer)
          }
          v['gcx-obsvCode'].forEach((obsvCode, index) => {
            set(state.gcx, obsvCode, {
              id: v.id,
              value: values[index],
              obsvCode: obsvCode
            })
          })
        } else if (v.dictValue === 'yx-hlcz') {
          let values = []
          if (v.val) {
            values = v.val.split(v.splicer)
          }

          v['hlcz-itemCode'].forEach((itemCode, index) => {
            set(state.hlcz, itemCode, {
              id: v.id,
              value: values[index],
              itemCode: itemCode,
              itemName: state.hlczEnumMap[itemCode]
            })
          })
        } else if (
          v.dictValue === 'yx-crl-in' ||
          v.dictValue === 'yx-crl-out'
        ) {
          let values = [],
            ids = [],
            itemCodes = [],
            sources = []
          if (v.val) {
            values = v.val.split(';')
          }
          if (v.id) {
            ids = v.id.split(';')
          }
          if (v.itemCode) {
            itemCodes = v.itemCode.split(';')
          }
          if (v.source) {
            sources = v.source.split(';')
          }
          values.forEach((c, index) => {
            const ioItem = {
              id: ids[index],
              itemCode: itemCodes[index],
              medication: c.split(' ')[0],
              nature: c.split(' ')[1],
              value:
                v.dictValue === 'yx-crl-in'
                  ? parseFloat(c.split(' ')[1])
                  : parseFloat(c.split(' ')[2]),
              isType: v.dictValue === 'yx-crl-in' ? 1 : 2,
              modelCode: v.dictValue === 'yx-crl-in' ? 'yx-in' : 'yx-out',
              source: sources[index]
            }
            if (state.io[v.dictValue]) {
              state.io[v.dictValue].push(ioItem)
            } else {
              set(state.io, v.dictValue, [ioItem])
            }
          })
        }
      })
    }

    function toAddCrlItem(dictValue) {
      let arr = []
      if (state.io[dictValue]) {
        arr = state.io[dictValue].filter(v => v.source === 'care')
      }
      if (arr && arr.length >= 5) {
        $notify({
          title: '提示',
          message: '最多添加五条，如需添加更多请至出入量页面添加',
          type: 'warning'
        })
      } else {
        const ioItem = {
          itemCode: '',
          modelCode: dictValue === 'yx-crl-in' ? 'yx-in' : 'yx-out',
          medication: '',
          value: '',
          isType: dictValue === 'yx-crl-in' ? 1 : 2,
          source: 'care'
        }
        if (state.io[dictValue]) {
          state.io[dictValue].push(ioItem)
        } else {
          set(state.io, dictValue, [ioItem])
        }
      }
    }

    function toRemoveCrlItem({ dictValue, index }) {
      $confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          state.io[dictValue].splice(index, 1)
        })
        .catch(() => {})
    }

    watch(
      () => props.cfgData,
      val => {
        if (val) {
          const cfgDataClone = JSON.parse(JSON.stringify(val))
          handleTreeData(cfgDataClone)
        }
      },
      {
        immediate: true,
        deep: true
      }
    )

    watch(
      () => props.recordData,
      val => {
        nextTick(() => {
          handleRecordData(val)
        })
      },
      {
        deep: true,
        immediate: true
      }
    )

    return {
      ...toRefs(state),
      evalDialogKeys,
      save,
      handelEval,
      toCloseEval,
      toUpdateEval,
      handleEvalFall,
      toCloseFall,
      toUpdateFall,
      handleEvalBraden,
      toUpdateBraden,
      toCloseBraden,
      handleValueChange,
      toAddCrlItem,
      toRemoveCrlItem
    }
  }
})
</script>

<style scoped lang="scss">
.dataRecord {
  height: 416px;
  overflow-y: auto;

  &::-webkit-scrollbar {
    width: 8px;
  }

  &::-webkit-scrollbar-thumb {
    border-radius: 8px;
    background: #aaa;
  }

  &::-webkit-scrollbar-track {
    border-radius: 8px;
  }

  .myForm {
    display: flex;
    flex-wrap: wrap;
  }

  .item {
    display: flex;
    flex-wrap: wrap;
  }

  .item2 {
    display: flex;

    .label {
      width: 80px;
      flex-shrink: 0;
    }

    .content {
      width: 100%;
      display: flex;
      align-items: center;
      flex-wrap: wrap;
    }
  }

  .leaf {
    display: flex;
    // align-items: center;
    margin-bottom: 14px;

    .label {
      white-space: nowrap;
      width: auto;
      line-height: 32px;
    }

    .content {
      padding-right: 20px;
    }

    .crlContent {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
    }
  }

  .crlLeaf {
    width: 100%;
  }

  .w-100 {
    width: 100%;
  }
}
</style>
